package com.appkubes.mall.admin.application.statis.controller;

import com.appkubes.common.Response;
import com.appkubes.common.constants.BaseConstants;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.admin.application.base.BaseController;
import com.appkubes.mall.admin.application.order.order.entity.model.OrderSum;
import com.appkubes.mall.admin.application.order.order.entity.model.SaleDataForWeek;
import com.appkubes.mall.admin.application.order.order.entity.model.UserConsume;
import com.appkubes.mall.admin.application.order.order.service.OrderServiceDepreciate;
import com.appkubes.mall.admin.application.statis.entity.SaleDataForWeekCollection;
import com.appkubes.mall.admin.application.statis.entity.UserPieData;
import com.appkubes.mall.admin.application.statis.entity.dto.UserStatisDataDTO;
import com.appkubes.mall.admin.application.user.user.service.impl.UserServiceImpl;
import com.appkubes.mall.core.entity.MallUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Api
@RestController
@RequestMapping("/sass_admin/Sindex")
@Slf4j
public class IndexControllerDepreciate extends BaseController {

    @Autowired
    UserServiceImpl userServiceImpl;

    @Autowired
    OrderServiceDepreciate orderServiceDepreciate;

    @ApiOperation("首页数据面板")
    @PostMapping("/index")
    public Response index() {
        Map<String, Object> map = new HashMap<>();
        // 用户数据
        UserStatisDataDTO userStatisDataDTO = new UserStatisDataDTO();

        userStatisDataDTO.setCount(userServiceImpl.countLog("`app_key`='" + getAppKey() + "'"));
        userStatisDataDTO.setTodayCount(userServiceImpl.countLog("(TO_DAYS(NOW()) - TO_DAYS( FROM_UNIXTIME(create_time)) = 0) AND app_key='" + getAppKey() + "'"));
        userStatisDataDTO.setYesterdayCount(userServiceImpl.countLog("(TO_DAYS(NOW()) - TO_DAYS( FROM_UNIXTIME(create_time)) = 1) AND app_key='" + getAppKey() + "'"));
        userStatisDataDTO.setMonthCount(userServiceImpl.countLog("(DATE_FORMAT(NOW(),'%Y%m') - DATE_FORMAT( FROM_UNIXTIME(create_time),'%Y%m') = 0) AND app_key='" + getAppKey() + "'"));

        // 获取用户购买占比
        UserPieData userPieData = new UserPieData();
        List<String> userIds = orderServiceDepreciate.getPayUserIds(getAppKey());
        userPieData.setBuyUser(userIds.size());
        userPieData.setNotBuyUser(userServiceImpl.countUnBuyUser(userIds, getAppKey()));

        // 用户消费排行
        List<UserConsume> consumes = orderServiceDepreciate.getUserConsumeRank(getAppKey());
        for (UserConsume consume : consumes) {
            MallUser user = userServiceImpl.getById(consume.getUserKey());
            if (user != null) {
                consume.setName(user.getName());
                consume.setImg(user.getImg());
            }
        }

        // 最近 7 天销售数据
        SaleDataForWeekCollection saleDataForWeekCollection = new SaleDataForWeekCollection();
        saleDataForWeekCollection.setAmountSums(new ArrayList<>());
        saleDataForWeekCollection.setDays(new ArrayList<>());
        saleDataForWeekCollection.setGoodsCounts(new ArrayList<>());
        List<SaleDataForWeek> saleDataForWeeks = orderServiceDepreciate.getSaleDataForWeek(getAppKey());
        for (SaleDataForWeek saleDataForWeek : saleDataForWeeks) {
            saleDataForWeekCollection.getAmountSums().add(saleDataForWeek.getAmountSum());
            saleDataForWeekCollection.getDays().add(saleDataForWeek.getDays());
            saleDataForWeekCollection.getGoodsCounts().add(saleDataForWeek.getGoodsCount());

        }

        // 订单数据
        Map<String, Integer> orderSumMap = new HashMap<>();
        try {
            List<OrderSum> orderSums = orderServiceDepreciate.getOrderSum(getAppKey());
            for (OrderSum orderSum : orderSums) {
                switch (orderSum.getState()) {
                    case BaseConstants.ORDER.UNPAY:
                        orderSumMap.put("dfk", orderSum.getRecordNum());
                        break;
                    case BaseConstants.ORDER.PAYSUCCESS:
                        orderSumMap.put("dps", orderSum.getRecordNum());
                        break;
                    case BaseConstants.ORDER.SENDING:
                        orderSumMap.put("psz", orderSum.getRecordNum());
                        break;
                    case BaseConstants.ORDER.ARRIVE:
                        orderSumMap.put("dzt", orderSum.getRecordNum());
                        break;
                    case BaseConstants.ORDER.COMPLETED:
                        orderSumMap.put("ywc", orderSum.getRecordNum());
                        break;
                    case BaseConstants.ORDER.CANCEL:
                        orderSumMap.put("yqx", orderSum.getRecordNum());
                        break;
                }
            }
        } catch (Exception e) {
            log.error("order statis error:", e);

        }
        map.put("user", userStatisDataDTO);
        map.put("user_pie", userPieData);
        map.put("user_order", consumes);
        map.put("saledata7", saleDataForWeekCollection);
        map.put("saledata8", orderSumMap);
        return Response.success(map);
    }

    @ApiOperation(value = "获取最近购买数据")
    @PostMapping("/saleData")
    public Response saleData(@RequestParam(defaultValue = "1") Integer type) {
        int day = (int) (DateUtils.getDayStartTime(new Date()).getTime() / 1000L); //获取今天凌晨的时间戳
        int time2 = day - 24 * 1 * 3600; //获取昨天凌晨的时间戳
        int time3 = day - 24 * 7 * 3600; //获取7天前凌晨的时间戳
        int time4 = day - 24 * 30 * 3600; //获取30天前凌晨的时间戳

        Map<String, Object> map = new HashMap<>();
        int createTime = 0;
        switch (type) {
            case 1:
                createTime = day;
                break;
            case 2:
                createTime = time2;
                break;
            case 3:
                createTime = time3;
                break;
            case 4:
                createTime = time4;
                break;
        }
        long saleNum = orderServiceDepreciate.getCountOfSaleDate(createTime);
        map.put("salenum", saleNum);
        double sum = orderServiceDepreciate.sumPayAmount(createTime);
        map.put("salemoney", sum);
        double avg = 0;
        if (saleNum != 0) {
            avg = sum / saleNum;
        }
        map.put("avesalemoney", String.format("%.2f", avg));
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("code", 0);
        returnMap.put("data", map);
        returnMap.put("msg", "success");
        return Response.success(returnMap);
    }
}
